import { _decorator, color, Component, director, find, instantiate, Label, Node, Prefab } from 'cc';
import { Core } from '../Core/Core';
import { EEquipmentType, EItemAffix, EItemType, getEquipmentTypeChinese, hasAffixes, IItem, isEquipment } from '../Item/Item';
import { BagItem } from '../Item/BagItem'; // 引入 BagItem 组件
import { IEquipment } from '../Item/Equipment';
import { EColor, EEvent, EPlayerType, ESubView, EView } from '../Config/Enum';
import { ResourceManager } from '../Core/ResourceManager';
import { PrefabPath } from '../Config/ResourceConfig';
import { Context } from '../Context';
import { ArsenalView } from '../Views/ArsenalView';

const { ccclass, property } = _decorator;

@ccclass('ItemDetail')
export class ItemDetail extends Component {
    private lbDesc: Label;
    private ndAffixParent: Node;
    private ndAffixParent_Wuxing: Node;
    private bagItemComp: BagItem; // 引用 BagItem 组件

    ndLbPrice: Node;
    lbProfession: Label;
    lbName: Label;
    lbWuxing: Label;
    lbAPDP: Label;
    ndBtnBuy: Node;
    //ndEquipmentSwitchView: Node;

    ndBtnEquipmentSwitch: Node;
    ndBtnStrengthen: Node;
    ndBtnSell: Node;
    ndBtnReroll: Node;
    ndBtnRemake: Node;

    protected onLoad(): void {
        //this.ndBG = this.node.getChildByName("BG");
        this.ndLbPrice = this.node.getChildByName("Board").getChildByName("Label_Price");
        this.lbProfession = this.node.getChildByName("Board").getChildByName("Profession").getComponent(Label);
        this.lbName = this.node.getChildByName("Board").getChildByName("Name").getComponent(Label);
        this.lbWuxing = this.node.getChildByName("Board").getChildByName("Wuxing").getComponent(Label);
        this.lbAPDP = this.node.getChildByName("Board").getChildByName("APDP").getComponent(Label);

        this.ndBtnEquipmentSwitch = this.node.getChildByName("Board").getChildByName("Button_Exchange");
        this.ndBtnStrengthen = this.node.getChildByName("Board").getChildByName("Button_Strengthen");
        this.ndBtnBuy = this.node.getChildByName("Board").getChildByName("Button_Buy");
        this.ndBtnSell = this.node.getChildByName("Board").getChildByName("Button_Sell");
        this.ndBtnReroll = this.node.getChildByName("Board").getChildByName("Button_Reroll");
        this.ndBtnRemake = this.node.getChildByName("Board").getChildByName("Button_Remake");
        
        // 获取 BagItem 节点和组件
        const bagItemNode = this.node.getChildByName("Board").getChildByName("BagItem");
        if (bagItemNode) {
            this.bagItemComp = bagItemNode.getComponent(BagItem);
        }
        
        this.lbDesc = this.node.getChildByName("Board").getChildByName("Desc").getComponent(Label);
        this.ndAffixParent = this.node.getChildByName("Board").getChildByName("Affixes");
        this.ndAffixParent_Wuxing = this.node.getChildByName("Board").getChildByName("Affixes_Wuxing");

        //this.ndEquipmentSwitchView = find("Canvas/EquipmentSwitchView") as Node
    }

    protected onEnable(): void {
        //this.ndBG.on(Node.EventType.TOUCH_END, this.onButtonCloseWindow, this);
        // if(Core.Instance.currentBagMode === "Shop"){
        //     // 显示购买按钮和价钱
        //     this.node.getChildByName("Board").getChildByName("Button_Buy").active = true;
        //     this.node.getChildByName("Board").getChildByName("Label_Price").active = true;
        // }else{
        //     // 隐藏购买按钮和价钱
        //     this.node.getChildByName("Board").getChildByName("Button_Buy").active = false;
        //     this.node.getChildByName("Board").getChildByName("Label_Price").active = false;
        // }


        this.checkElementVisibility();
        this.refreshItemDetail();
    }

    protected onDisable(): void {
        //this.ndBG.off(Node.EventType.TOUCH_END, this.onButtonCloseWindow, this);
        this.node.destroy();
    }

    private refreshItemDetail(): void {
        const currentItem = Core.Instance.currentItem;
        if (!currentItem) return;
        
        // 使用 BagItem 组件初始化物品显示
        if (this.bagItemComp) {
            this.bagItemComp.init(currentItem);
        }


            // 使用类型守卫安全访问装备特有属性
        if (isEquipment(currentItem)) {
            // 现在 TypeScript 知道 currentItem 是 IEquipment
            this.showEquipmentDetails(currentItem);
        } else {
            this.showBasicItemDetails(currentItem);
        }


        
}



    
    // 专门处理装备的显示
    private showEquipmentDetails(equipment: IEquipment): void {
        // 显示物品名称（带中文装备类型）
        const chineseType = getEquipmentTypeChinese(equipment.equipmentType);
        this.lbName.string = `${equipment.name} [${chineseType}]`;
        // 显示物品描述
        this.lbDesc.string = equipment.desc || "无描述";
        // 显示职业限制
        this.showProfessionRestrictions(equipment);
        // 显示装备APDP属性
        if(equipment.ap === 0){
            this.lbAPDP.string = `防御力: ${equipment.dp}`;
        }else{
            this.lbAPDP.string = `攻击力: ${equipment.ap}`;
        }

        // 如果时装备，显示物品五行
        if (equipment.itemType === EItemType.Equipment) {
            let wuxing = (equipment as IEquipment).wuxing
            this.lbWuxing.string = wuxing

            // 直接从EColor枚举中获取对应的颜色
            let colorHex = EColor[wuxing as keyof typeof EColor];
            if (colorHex) {
                this.lbWuxing.color = color().fromHEX(colorHex);
            } else {
                this.lbWuxing.color = color().fromHEX(EColor.White);
            }


        }else{
            this.lbWuxing.string = "";
            this.lbWuxing.color = color().fromHEX(EColor.White);

        }
        


        this.showAffixes(equipment.affixes);
        this.showAffixes_Wuxing(equipment.affixes_wuxing);

                // 显示职业限制
        //if (equipment.equipmentType === EEquipmentType.Weapon) {
            
        //}

        //if (Core.Instance.currentView === EView.ArsenalView && Core.Instance.currentSubView === ESubView.Shop) {
            this.loadPrice(equipment);
        //}

    }



// 处理基础物品显示
private showBasicItemDetails(item: IItem): void {
    this.lbName.string = item.name;
    this.lbWuxing.string = "";
    this.lbProfession.string = "";
    this.lbAPDP.string = "";
    this.lbDesc.string = item.desc || "";

        // 对于非装备物品，如果有词缀也显示（比如宝石）
    if (hasAffixes(item)) {
        this.showAffixes(item.affixes);
    }

    this.loadPrice(item);
}


     loadPrice(item: IItem): void {
        // 显示价格（假设每个物品有一个 price 属性）
        if (this.ndLbPrice && item.price !== undefined) {
            this.ndLbPrice.getComponent(Label).string = `价格: ${item.price} `;
        }
    }


    private showProfessionRestrictions(equipment: IEquipment): void {
        
    
        // 如果是武器，则显示职业限制
        if (equipment.equipmentType == EEquipmentType.Weapon) {
            let profession = equipment.profession
            switch(profession){
                case []:
                    this.lbProfession.string = "通用"
                    break;
                default:
                    let s = "适合:"
                    for (const p of profession) {
                        let pro = Core.Instance.getProfessionDesc(p as EPlayerType)
                        s += pro + " "
                    }
                    this.lbProfession.string = s
                    break;

                        
            }
        }else{
            this.lbProfession.string = ""
        }
    }


    // 显示词缀
    private showAffixes(affixes: EItemAffix[]): void {
        // 隐藏所有词缀节点
        this.ndAffixParent.children.forEach(node => node.active = false); // 
        console.log("222222222显示词缀:", affixes);
        
        // 显示当前装备的词缀
        if (affixes && affixes.length > 0) {
            for (let i = 0; i < affixes.length; i++) {
                console.log("22222222显示词缀节点:", this.ndAffixParent.children[i]);
                const affixNode = this.ndAffixParent.children[i];
                if (affixNode) {
                    affixNode.getComponent(Label).string = affixes[i].description;
                    affixNode.active = true;
                    console.log("22222222显示词缀节点激活:", affixNode);
                    console.log("22222222显示词缀内容:", affixes[i].description);
                }
            }
        }
    }

    // 显示五行词缀
    private showAffixes_Wuxing(affixes_wuxing: EItemAffix[]): void {
        // 隐藏所有词缀节点
        this.ndAffixParent_Wuxing.children.forEach(node => node.active = false);
        console.log("222222222显示五行词缀:", affixes_wuxing);
        
        // 显示当前装备的词缀
        if (affixes_wuxing && affixes_wuxing.length > 0) {
            for (let i = 0; i < affixes_wuxing.length; i++) {
                console.log("22222222显示五行词缀节点:", this.ndAffixParent_Wuxing.children[i]);
                const affixNode = this.ndAffixParent_Wuxing.children[i];
                if (affixNode) {
                    affixNode.getComponent(Label).string = affixes_wuxing[i].description;
                    affixNode.active = true;
                    // 如果已激活，显示激活的颜色 EColor.WuxingActive
                    if (affixes_wuxing[i].isActive) {
                        affixNode.getComponent(Label).color = color().fromHEX(EColor.WuxingActive);
                    } else {
                        affixNode.getComponent(Label).color = color().fromHEX(EColor.WuxingDeactive);
                        
                    }
                    console.log("22222222显示五行词缀节点激活:", affixNode);
                    console.log("22222222显示五行词缀内容:", affixes_wuxing[i].description);
                }
            }
        }
    }

    private onButtonCloseWindow(): void {
        this.node.active = false;
    }

    onButtonBuy(): void {
        // 购买逻辑
        Core.Instance.event.emit(EEvent.ShopBuy);
            // 先隐藏，延迟销毁以避免潜在问题
    this.node.active = false;
        
        




    }

    showGemSlots() {
        
    }

    /**
     * 显示装备切换视图
     * 该方法用于在Canvas上创建并显示装备切换界面
     */
    showEquipmentSwitchView() {
        
        // 获取BagItem预制体
        const prefab = ResourceManager.Instance.getResourceCache().get(PrefabPath.EquipmentSwitchView) as Prefab;
        console.log("ItemDetail预制体:", prefab);

        const EquipmentSwitchViewNode = instantiate(prefab);

        EquipmentSwitchViewNode.setParent(find("Canvas") as Node);
        EquipmentSwitchViewNode.active = true;
        Context.ndEquipmentSwitchView = EquipmentSwitchViewNode;
    }

    checkElementVisibility() {
        console.log("checkElementVisibility, Core.Instance.currentView:", Core.Instance.currentView);
        console.log("checkElementVisibility, Core.Instance.currentSubView:", Core.Instance.currentSubView);


        // 如果是Battle场景，则仅展示信息不展示任何按钮
        if (director.getScene().name === "Battle") {
                this.ndBtnEquipmentSwitch.active = false
                this.ndBtnStrengthen.active = false
                this.ndLbPrice.active = false
                this.ndBtnBuy.active = false
                this.ndBtnSell.active = false
                this.ndBtnReroll.active = false
                this.ndBtnRemake.active = false
        }
        // 如果是Main场景的ArsenalView，则根据当前子视图展示不同的按钮
        else if(Core.Instance.currentView === EView.ArsenalView ){
            if(Core.Instance.currentSubView === ESubView.Shop){
                this.ndBtnEquipmentSwitch.active = false
                this.ndBtnStrengthen.active = false
                this.ndLbPrice.active = true
                this.ndBtnBuy.active = true
                this.ndBtnSell.active = false
                this.ndBtnReroll.active = false
                this.ndBtnRemake.active = false

            }else if(Core.Instance.currentSubView === ESubView.Bag){
                this.ndBtnEquipmentSwitch.active = false
                this.ndBtnStrengthen.active = true
                this.ndLbPrice.active = false
                this.ndBtnBuy.active = false
                this.ndBtnSell.active = true
                this.ndBtnReroll.active = true
                this.ndBtnRemake.active = true

                
            }

        }else if(Core.Instance.currentView === EView.PlayerView){
            this.ndBtnEquipmentSwitch.active = true
            this.ndBtnStrengthen.active = true
            this.ndLbPrice.active = false
            this.ndBtnBuy.active = false
            this.ndBtnSell.active = false
            this.ndBtnReroll.active = true
            this.ndBtnRemake.active = true
        }

    }

    // onButtonEquipmentSwitch() {
    //     console.log("onButtonEquipmentSwitch");
    //     // 切换装备界面
    //     Context.ndEquipmentSwitchView.active = !Context.ndEquipmentSwitchView.active; // 切换显示状态
    //     //Core.Instance.event.emit(EEvent.SwitchView, Context.ArsenalView);
    //     //Core.Instance.event.emit(EEvent.SwitchView, Context.PlayerView);
    // }

    onButtonStrengthen() {
        // 强化逻辑
        console.log("onButtonStrengthen");
        Context.ndPlayerView.active = false;
        Context.ndArsenalView.active = true;
        // Context.ndArsenalView.getChildByName('Bag').active = false;
        // Context.ndArsenalView.getComponent(ArsenalView).onButtonOpenForge();
        Core.Instance.event.emit(EEvent.OpenForgeView);
        this.node.active = false;

        
    }

    onButtonSell() {
        // 出售逻辑
        console.log("出售物品onButtonSell");
        console.log("出售物品Core.Instance.currentItem",Core.Instance.currentItem);
        console.log("出售物品Core.Instance.currentItem.price",Core.Instance.currentItem.price);
        console.log("出售物品Core.Instance.currentItem.id",Core.Instance.currentItem.id);

        Core.Instance.bag.removeItem(Core.Instance.currentItem);
        Core.Instance.gold += Core.Instance.currentItem.price/2;
        Core.Instance.event.emit(EEvent.ItemSold)
        Core.Instance.event.emit(EEvent.ResourceChanged); // 通知其他组件更新资源显示
        this.node.active = false;
        Core.Instance.save();
    }



    onButtonReroll() {
        // 重铸逻辑
        console.log("重铸物品onButtonReroll");
        this.node.active = false;
    }

    onButtonRemake() {
        // 重做逻辑

        // 弹出提示，是否确认出售 TODO


        this.node.active = false;
    }



}